package leetcode_core.leetcode_1;

public class InsertIntoBST {
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode insertIntoBST(TreeNode root, int val) {
        if(root == null){
            //遍历到合适的位置了,进行插入,注意将节点new出来后是交给递归来连接的
            return new TreeNode(val);
        }
        //题干中说没有这种样例,但是如果有的话就直接返回就行了
        if(root.val == val){
            return root;
        }
        //val的值要大,`左小右大,那么我应该将这个节点连接到右子树上`
        if(root.val < val){
            root.right = insertIntoBST(root.right,val);
        }
        if(root.val > val){
            root.left = insertIntoBST(root.left,val);
        }
        //完毕之后将链接好的树给返回回去就好了
        return root;
    }
}
